package pl.ppsoft.fixlang;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import pl.ppsoft.fixlang.common.HandleEvent;
import pl.ppsoft.fixlang.common.ListViewAdapter;
import pl.ppsoft.fixlang.common.ModeHandleEvent;
import pl.ppsoft.fixlang.enums.LearnModeEnum;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class LessonsActivity extends ListActivity {	

	private static final int LESSON_ROW_HEIGHT = 46;
	private static final int GLOBAL_ROW_HEIGHT = 38;
	
	private static final int REQUEST_CODE_PREFERENCES = 1;
	private static final int REQUEST_CODE_LEARNING = 2;

	public static final int RESET_LESSON_DIALOG = 1;
	public static final int CROSS_LEARN_DIALOG = 2;
	public static final int LESSON_MENU_DIALOG = 3;
        	
    private DbAdapter db;
    private ArrayList<Long> lessonIds = new ArrayList<Long>();
    private int wordcount, questioning, answering, writing, listening;
	private int questioningColIndex, answeringColIndex, writingColIndex, listeningColIndex, countColIndex;
	private CustomCursorAdapter  adapter;
	private String sortCol = DbAdapter.LESSON_ROWID;
	private boolean sortDesc = false;
	private long selectedLessonId;
	private Menu mainMenu;	
	private CheckBox selectionCheck;
	private SharedPreferences settings;
	private float density;
	private View itemQuestioning, itemAnswering, itemWriting, itemListening;
	private boolean questioningEnabled, answeringEnabled, listeningEnabled, writingEnabled;
	private int crossNumber;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lessons);
        
        this.settings = PreferenceManager.getDefaultSharedPreferences(this);
        Editor editor = this.settings.edit();
        editor.remove(FixLangActivity.MODIFY_PREFERENCE_FLAG);
        editor.remove(FixLangActivity.MODIFY_HISTORY_FLAG);
        editor.commit();
        
        this.crossNumber = Integer.parseInt( this.settings.getString(ConfigActivity.CROSS_DEFAULT_PREFERENCE, "50") );
        this.questioningEnabled = this.enableMethods(ConfigActivity.QUESTIONING_METHOD_PREFERENCE, R.id.questioning_chart, true, true);
        this.answeringEnabled = this.enableMethods(ConfigActivity.ANSWERING_METHOD_PREFERENCE, R.id.answering_chart, true, true);
        this.listeningEnabled = this.enableMethods(ConfigActivity.LISTENING_METHOD_PREFERENCE, R.id.listening_chart, false, this.settings.getBoolean(ConfigActivity.SPEECH_PREFERENCE, false));
        this.writingEnabled = this.enableMethods(ConfigActivity.WRITING_METHOD_PREFERENCE, R.id.writing_chart, true, true);
        
        db = new DbAdapter(this);
        db.open();
        this.density = getResources().getDisplayMetrics().density;
        this.selectionCheck = (CheckBox)findViewById( R.id.selection_check );
        
        registerForContextMenu( getListView() );        
                
        loadLessons(sortCol, sortDesc);
        setGlobalChart();
    }
	
	@Override
	protected void onDestroy() {
		db.close();

		super.onDestroy();
	}
	
	@Override
	protected void onResume() {
        if ( this.settings.getBoolean(FixLangActivity.MODIFY_PREFERENCE_FLAG, false) ) {
            Editor editor = this.settings.edit();
            editor.remove(FixLangActivity.MODIFY_PREFERENCE_FLAG);
            editor.commit();

            this.refreshLessons();
        }
		
		super.onResume();
	}

	private void loadLessons( String sort, boolean desc ) {
		if ( adapter != null ) {
			adapter.close();
		}

		Cursor lessonsCursor = db.fetchChartLessons(sort, desc);
        startManagingCursor(lessonsCursor);

        answeringColIndex = lessonsCursor.getColumnIndexOrThrow(DbAdapter.LESSON_ANSWERING); 
        questioningColIndex = lessonsCursor.getColumnIndexOrThrow(DbAdapter.LESSON_QUESTIONING); 
		writingColIndex = lessonsCursor.getColumnIndexOrThrow(DbAdapter.LESSON_WRITING);
		listeningColIndex = lessonsCursor.getColumnIndexOrThrow(DbAdapter.LESSON_LISTENING);
		countColIndex = lessonsCursor.getColumnIndexOrThrow(DbAdapter.LESSON_WORD_COUNT); 

        String[] from = new String[]{DbAdapter.LESSON_NAME, DbAdapter.LESSON_WORD_COUNT, DbAdapter.LESSON_QUESTIONING, DbAdapter.LESSON_ANSWERING, DbAdapter.LESSON_WRITING, DbAdapter.LESSON_LISTENING};
        int[] to = new int[]{R.id.lesson, R.id.wordcount, R.id.questioning_chart, R.id.answering_chart, R.id.writing_chart, R.id.listening_chart};
        
        adapter = new CustomCursorAdapter(this, R.layout.lessons_row, lessonsCursor, from, to);	        	        
        setListAdapter(adapter);                
    }

    private void doSyncLessons() {
        String url = settings.getString(ConfigActivity.URL_PREFERENCE, ""); 
        HandleEvent handler = new HandleEvent() {			
			@Override
			public boolean doEvent() {
				refreshLessons();
				
		        Editor editor = settings.edit();
		        editor.putBoolean(FixLangActivity.MODIFY_PREFERENCE_FLAG, true);
		        editor.commit();
				
				return true;
			}
		};
        
    	new SyncLessonsTask(this, db, url, handler ).execute();    	
    }
    
    public void onSelectionCheckClick(View view) {
    	adapter.clearChecked();
    	ListView list = this.getListView();
    	for (int i = 0; i < list.getChildCount(); i ++ ) {
    		View child = list.getChildAt(i);
    		((CheckBox)child.findViewById( R.id.checklesson )).setChecked(false);
    	}
    	selectionCheck.setEnabled(false);
    }
    
    private void refreshLessons() {
    	adapter.requery();
    	setGlobalChart();
    }
    
    private void setGlobalChart() {
    	int max = db.fetchGlobalWords(null);
    	int aq = db.fetchGlobalWords(DbAdapter.WORD_ANSWERING);
    	int qa = db.fetchGlobalWords(DbAdapter.WORD_QUESTIONING);
    	int w = db.fetchGlobalWords(DbAdapter.WORD_WRITING);
    	int l = db.fetchGlobalWords(DbAdapter.WORD_LISTENING);
    	
    	findViewById( R.id.answering_chart ).getLayoutParams().height = calcChartHeight( GLOBAL_ROW_HEIGHT, aq, max );
    	findViewById( R.id.questioning_chart ).getLayoutParams().height = calcChartHeight( GLOBAL_ROW_HEIGHT, qa, max );
    	findViewById( R.id.listening_chart ).getLayoutParams().height = calcChartHeight( GLOBAL_ROW_HEIGHT, l, max );
    	findViewById( R.id.writing_chart ).getLayoutParams().height = calcChartHeight( GLOBAL_ROW_HEIGHT, w, max );    	    	
    }
    
    private int calcChartHeight( int height, int count, int max ) {
		float res = 0;
		if ( max > 0 ) {						
			res = (float)count * ( (float)height / (float)max ) * density;
		}					
		return Math.round( res );					
	}


    
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.mainMenu= menu; 

		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.lessons_menu, menu);
        
        return super.onCreateOptionsMenu(menu);    
    }

    @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
        this.mainMenu.findItem(R.id.menu_sync).setVisible(this.settings.getBoolean(ConfigActivity.SYNC_PREFERENCE, false) );
        this.mainMenu.findItem(R.id.menu_sort_answering).setVisible(this.answeringEnabled);
        this.mainMenu.findItem(R.id.menu_sort_questioning).setVisible(this.questioningEnabled);
        this.mainMenu.findItem(R.id.menu_sort_listening).setVisible(this.listeningEnabled);
        this.mainMenu.findItem(R.id.menu_sort_writing).setVisible(this.writingEnabled);

    	return super.onPrepareOptionsMenu(menu);
	}
    
	public void onCrossButton(View view) {
		this.showDialog(CROSS_LEARN_DIALOG);
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
	        case R.id.menu_sync:
            	this.doSyncLessons();
                return true;
            case R.id.menu_config:
            	Intent config = new Intent(this, ConfigActivity.class);
            	config.putExtra(ConfigActivity.PREFERENCE_MODE_PARAM, R.xml.lesson_preferences);
            	startActivityForResult(config, REQUEST_CODE_PREFERENCES);                  	
                return true;
            case R.id.menu_sort_name:
            	sortList( item,DbAdapter.LESSON_NAME, false ); 
            	return true;
            case R.id.menu_sort_words:
            	sortList( item,DbAdapter.LESSON_WORD_COUNT, true ); 
            	return true;
            case R.id.menu_sort_answering:
            	sortList( item,DbAdapter.LESSON_ANSWERING, true ); 
            	return true;
            case R.id.menu_sort_questioning:
            	sortList( item,DbAdapter.LESSON_QUESTIONING, true ); 
            	return true;
            case R.id.menu_sort_listening:
            	sortList( item,DbAdapter.LESSON_LISTENING, true ); 
            	return true;
            case R.id.menu_sort_writing:
            	sortList( item,DbAdapter.LESSON_WRITING, true ); 
            	return true;
            default:
                return super.onOptionsItemSelected(item);                
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.reset_menu, menu);    		
    }
        
    @Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case RESET_LESSON_DIALOG:
        	return new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setMessage(R.string.lesson_really_reset)
            .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                	db.resetWords( selectedLessonId );
                	refreshLessons();
                }

            })
            .setNegativeButton(R.string.btn_no, null)
            .create();			
		case CROSS_LEARN_DIALOG:
            final View learnPeriodView = LayoutInflater.from(this).inflate(R.layout.learn_dialog, null); 
			final ToggleButton crossRepeat = (ToggleButton)learnPeriodView.findViewById( R.id.lesson_repeat ); 
                                                   			
            final List<View> crossMenuList = new ArrayList<View>();
            if ( this.answeringEnabled ) {
            	crossMenuList.add( this.crossMenuItem( R.layout.lesson_menu_check, R.string.menu_answering, LearnModeEnum.ANSWERING, true, crossRepeat, null ) );
            }
            if ( this.questioningEnabled ) {
            	crossMenuList.add( this.crossMenuItem( R.layout.lesson_menu_check, R.string.menu_questioning, LearnModeEnum.QUESTIONING, true, crossRepeat, null ) );
            }
            if ( this.listeningEnabled ) {
				crossMenuList.add( this.crossMenuItem( R.layout.lesson_menu_check, R.string.menu_listening, LearnModeEnum.LISTENING, false, crossRepeat, null ) );
			}
            if ( this.writingEnabled ) {
            	crossMenuList.add( this.crossMenuItem( R.layout.lesson_menu_check, R.string.menu_writing, LearnModeEnum.WRITING, false, crossRepeat, null ) );
            }
			if ( this.settings.getBoolean(ConfigActivity.VOICE_PREFERENCE, false) ) {
				crossMenuList.add( this.crossMenuItem( R.layout.lesson_menu_item, R.string.menu_pronounce, LearnModeEnum.PRONOUNCE, false, crossRepeat, null ) );
			}
			
			if ( this.questioningEnabled || this.answeringEnabled || this.listeningEnabled || this.writingEnabled ) {
				crossMenuList.add( this.crossMenuItem( R.layout.lesson_menu_center, R.string.menu_random, LearnModeEnum.RANDOM, false, crossRepeat, new HandleEvent() {
					
					@Override
					public boolean doEvent() {
						List<LearnModeEnum> modeList = new ArrayList<LearnModeEnum>();					
						for (View view : crossMenuList) {
							CheckBox checkBox = (CheckBox)view.findViewById( R.id.randomcheck );
							if ( checkBox != null && checkBox.isChecked() ) {
								modeList.add( ((ModeHandleEvent)view.getTag()).getMode() );
							}
						}
						
						if ( modeList.isEmpty() ) {
							Toast.makeText(LessonsActivity.this, R.string.random_check, Toast.LENGTH_SHORT).show();
							return false;
						} else {		
							
							
							Intent intent = new Intent(LessonsActivity.this, LearnActivity.class);
							intent.putExtra(LearnActivity.LEARN_MODE_PARAM, LearnModeEnum.RANDOM);
				        	intent.putExtra(LearnActivity.LEARN_CROSS_NUMBER, crossNumber);		        	
				        	intent.putExtra(LearnActivity.REPEAT_LEARN, crossRepeat.isChecked());
				        	intent.putExtra(LearnActivity.LEARN_RANDOM_LIST, (Serializable)modeList);
							intent.putExtra(LearnActivity.LESSONS_PARAM, (Serializable)getSelectedLessonIds());												
							
				        	startActivityForResult(intent, REQUEST_CODE_LEARNING);
				        	return true;
						}					
					}
					
				}));
			} else {
	    		return new AlertDialog.Builder(this)
	    		.setMessage(R.string.methods_empty)
	    		.setNeutralButton(R.string.btn_ok, null )                    
	    		.create();        		
			}
			
            final AlertDialog crossDialog = new AlertDialog.Builder(this)
								            .setTitle( MessageFormat.format( getString(R.string.learn_cross_title), this.crossNumber) )
								            .setInverseBackgroundForced(true)
								            .setView(learnPeriodView)
								            .create(); 
            
            ListView commandList = (ListView) learnPeriodView.findViewById(R.id.command_list);
            commandList.setAdapter( new ListViewAdapter( crossMenuList ) );
            commandList.setOnItemClickListener( new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> listview, View v, int position, long id) {
					if ( ((HandleEvent)v.getTag()).doEvent() ) {
						crossDialog.dismiss();
					}
            	}
			
            });   
            return crossDialog;
		case LESSON_MENU_DIALOG:
			View menuDialogView = LayoutInflater.from(this).inflate(R.layout.learn_dialog, null);
			final ToggleButton repeat = (ToggleButton)menuDialogView.findViewById( R.id.lesson_repeat ); 
			
			final List<View> viewList = new ArrayList<View>();			
            if ( this.answeringEnabled ) {
            	viewList.add( itemAnswering = this.lessonMenuItem(R.layout.lesson_answering_menu, 0, LearnModeEnum.ANSWERING, true, repeat, null ) );
            }
            if ( this.questioningEnabled ) {            
            	viewList.add( itemQuestioning = this.lessonMenuItem(R.layout.lesson_questioning_menu, 0, LearnModeEnum.QUESTIONING, true, repeat, null ) );
            }
			if ( this.listeningEnabled ) {
				viewList.add( itemListening = this.lessonMenuItem(R.layout.lesson_listening_menu, 0, LearnModeEnum.LISTENING, false, repeat, null ) );
			}
			if ( this.writingEnabled ) {
				viewList.add( itemWriting = this.lessonMenuItem(R.layout.lesson_writing_menu, 0, LearnModeEnum.WRITING, false, repeat, null ) );
			}
			if ( this.settings.getBoolean(ConfigActivity.VOICE_PREFERENCE, false) ) {
				viewList.add( this.lessonMenuItem(R.layout.lesson_menu_item, R.string.menu_pronounce, LearnModeEnum.PRONOUNCE, false, repeat, null ) );				
			}
			if ( this.questioningEnabled || this.answeringEnabled || this.listeningEnabled || this.writingEnabled ) {
				viewList.add( this.lessonMenuItem(R.layout.lesson_menu_center, R.string.menu_random, LearnModeEnum.RANDOM, false, repeat, new HandleEvent() {
					
					@Override
					public boolean doEvent() {
						List<LearnModeEnum> modeList = new ArrayList<LearnModeEnum>();					
						for (View view : viewList) {
							CheckBox checkBox = (CheckBox)view.findViewById( R.id.randomcheck );
							if ( checkBox != null && checkBox.isChecked() ) {
								modeList.add( ((ModeHandleEvent)view.getTag()).getMode() );
							}
						}
						
						if ( modeList.isEmpty() ) {
							Toast.makeText(LessonsActivity.this, R.string.random_check, Toast.LENGTH_SHORT).show();
							return false;
						} else {					
							Intent intent = new Intent(LessonsActivity.this, LearnActivity.class);
							intent.putExtra(LearnActivity.LEARN_MODE_PARAM, LearnModeEnum.RANDOM);
							intent.putExtra(LearnActivity.LESSONS_PARAM, lessonIds);
							intent.putExtra(LearnActivity.REPEAT_LEARN, repeat.isChecked());
							intent.putExtra(LearnActivity.LEARN_RANDOM_LIST, (Serializable)modeList);
				        	startActivityForResult(intent, REQUEST_CODE_LEARNING);
				        	return true;
						}
					}
				}));
			} else {
	    		return new AlertDialog.Builder(this)
	    		.setMessage(R.string.methods_empty)
	    		.setNeutralButton(R.string.btn_ok, null )                    
	    		.create();        		
			}
									
            final AlertDialog lessonMenuDialog = new AlertDialog.Builder(this)
            									 .setInverseBackgroundForced(true)
            									 .setTitle(R.string.lesson_learn_title)
            									 .setView(menuDialogView)
            									 .create(); 
						
			ListView menuList = (ListView)menuDialogView.findViewById( R.id.command_list );			
			menuList.setAdapter( new ListViewAdapter( viewList ) );
			menuList.setOnItemClickListener( new OnItemClickListener() {
				
            	@Override
				public void onItemClick(AdapterView<?> listview, View v, int position, long id) {				
            		if ( ((HandleEvent)v.getTag()).doEvent() ) {
            			lessonMenuDialog.dismiss();
            		}
				}
            });
						            
            return lessonMenuDialog;
		default:
	    	return super.onCreateDialog(id);
		}
	}
    
    private View lessonMenuItem( int menuItem, int menuLabel, LearnModeEnum mode, boolean checked, ToggleButton repeat, HandleEvent handler) {
		View view = LayoutInflater.from(this).inflate(menuItem, null);
		if ( menuLabel > 0 ) {
			((TextView)view.findViewById(R.id.menu_item)).setText( menuLabel );
		}
		if ( checked ) {
			((CheckBox)view.findViewById(R.id.randomcheck)).setChecked(true);
		}
		if (handler == null) {		
			view.setTag( new HandleLearnEvent( mode, repeat ) );
		} else {
			view.setTag( handler );
		}
		return view;
    }

    private class HandleLearnEvent implements ModeHandleEvent {
    	private LearnModeEnum mode;
    	private ToggleButton repeat;
    	public HandleLearnEvent(LearnModeEnum mode, ToggleButton repeat) {
    		this.mode = mode;
    		this.repeat = repeat;
    	}
    	
		@Override
		public boolean doEvent() {
			Intent intent = new Intent(LessonsActivity.this, LearnActivity.class);
			intent.putExtra(LearnActivity.LEARN_MODE_PARAM, mode);
			intent.putExtra(LearnActivity.REPEAT_LEARN, repeat.isChecked());
			intent.putExtra(LearnActivity.LESSONS_PARAM, lessonIds);
        	startActivityForResult(intent, REQUEST_CODE_LEARNING);
        	return true;
		}

		@Override
		public LearnModeEnum getMode() {
			return mode;
		}
    	
    }
    
    private View crossMenuItem( int menuItem, int menuLabel, LearnModeEnum mode, boolean checked, ToggleButton repeat, HandleEvent handler) {
		View view = LayoutInflater.from(this).inflate(menuItem, null);
		((TextView)view.findViewById(R.id.menu_item)).setText( menuLabel );
		if ( checked ) {
			((CheckBox)view.findViewById(R.id.randomcheck)).setChecked(true);
		}
		if ( handler == null ) {
			view.setTag( new HandleCrossEvent( mode, repeat ) );
		} else {
			view.setTag( handler );
		}
		return view;
    }
    
    private class HandleCrossEvent implements ModeHandleEvent {
    	private LearnModeEnum mode;
    	private ToggleButton repeat;
    	public HandleCrossEvent(LearnModeEnum mode, ToggleButton repeat) {
    		this.mode = mode;
    		this.repeat = repeat;
    	}
    	
		@Override
		public boolean doEvent() {
        	Intent intent = new Intent(LessonsActivity.this, LearnActivity.class);
			intent.putExtra(LearnActivity.LEARN_MODE_PARAM, mode);
        	intent.putExtra(LearnActivity.LEARN_CROSS_NUMBER, crossNumber);
        	intent.putExtra(LearnActivity.REPEAT_LEARN, repeat.isChecked());
			intent.putExtra(LearnActivity.LESSONS_PARAM, (Serializable)getSelectedLessonIds());												        	
			startActivityForResult(intent, REQUEST_CODE_LEARNING);
			return true;
		}
    	
		@Override
		public LearnModeEnum getMode() {
			return mode;
		}		
    }

    private List<Long> getSelectedLessonIds() {
    	ListView l = getListView();
    	List<Long> ids = new ArrayList<Long>();
    	List<Integer> selPos = adapter.selectedPositions();
    	for (Integer pos : selPos) {
	    	ids.add( l.getItemIdAtPosition(pos) );			
		}    	
    	return ids;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);

        switch (id) {
            case LESSON_MENU_DIALOG:
            	if ( this.answeringEnabled ) {
            		this.updateChartItem( itemAnswering, this.answering );
            	}
            	if ( this.questioningEnabled ) {
            		this.updateChartItem( itemQuestioning, this.questioning );
            	}
            	if ( this.listeningEnabled ) {
            		this.updateChartItem( itemListening, this.listening );
            	}
            	if ( this.writingEnabled ) {
            		this.updateChartItem( itemWriting, this.writing );
            	}
            	break;
        }
    }
    
    private void updateChartItem( View item, int progress ) {
    	((TextView)item.findViewById( R.id.progress_value )).setText( "" + progress );
    	ProgressBar pb = (ProgressBar)item.findViewById( R.id.chart_progress );
    	pb.setMax( this.wordcount );
    	pb.setProgress( progress );    	
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
	        case R.id.menu_reset:
	        	selectedLessonId = ((AdapterContextMenuInfo) item.getMenuInfo()).id;
	        	this.showDialog(RESET_LESSON_DIALOG);        	
	        	return true;	
	        default:
	            return super.onContextItemSelected(item);
        }    	
    }

    private void sortList(MenuItem item, String name, boolean desc) {
    	if ( sortCol.equals( name ) ) {
    		sortDesc = !sortDesc;
    	} else {
    		sortDesc = desc;
    	}
    	item.setChecked(true);
    	sortCol = name;
    	loadLessons( name, sortDesc );     	
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	this.lessonIds.clear();
    	
    	if ( !((CheckBox)v.findViewById(R.id.checklesson)).isChecked() ) {
	    	Cursor row = (Cursor)l.getItemAtPosition(position);
	    	this.wordcount = row.getInt( countColIndex );
	    	this.questioning = row.getInt( questioningColIndex );
	    	this.answering = row.getInt( answeringColIndex );
	    	this.writing = row.getInt( writingColIndex );
	    	this.listening = row.getInt( listeningColIndex );
	    	
	    	this.lessonIds.add( id );
    	} else {
    		this.wordcount = 0;
	    	this.questioning = 0;
	    	this.answering = 0;
	    	this.writing = 0;
	    	this.listening = 0;
    	}
    	
    	List<Integer> selPos = adapter.selectedPositions();
    	for (Integer pos : selPos) {
	    	Cursor row = (Cursor)l.getItemAtPosition(pos);
	    	this.wordcount = row.getInt( countColIndex );
	    	this.questioning += row.getInt( questioningColIndex );
	    	this.answering += row.getInt( answeringColIndex );
	    	this.writing += row.getInt( writingColIndex );
	    	this.listening += row.getInt( listeningColIndex );
	    	this.lessonIds.add( l.getItemIdAtPosition(pos) );			
		}
    	    	    
    	showDialog( LESSON_MENU_DIALOG );
    	
    	super.onListItemClick(l, v, position, id);
    }

	private boolean enableMethods( String preference, int chart, boolean def, boolean extra) {
        boolean result = this.settings.getBoolean(preference, def) && extra;
        findViewById( chart ).setVisibility(result?View.VISIBLE:View.GONE);
        return result;
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_CODE_PREFERENCES) {
            MenuItem item = this.mainMenu.findItem(R.id.menu_sync);
            item.setVisible(this.settings.getBoolean(ConfigActivity.SYNC_PREFERENCE, false) );
            
            this.crossNumber = Integer.parseInt( this.settings.getString(ConfigActivity.CROSS_DEFAULT_PREFERENCE, "50") );
            this.questioningEnabled = this.enableMethods(ConfigActivity.QUESTIONING_METHOD_PREFERENCE, R.id.questioning_chart, true, true);
            this.answeringEnabled = this.enableMethods(ConfigActivity.ANSWERING_METHOD_PREFERENCE, R.id.answering_chart, true, true);
            this.listeningEnabled = this.enableMethods(ConfigActivity.LISTENING_METHOD_PREFERENCE, R.id.listening_chart,  false, this.settings.getBoolean(ConfigActivity.SPEECH_PREFERENCE, false));
            this.writingEnabled = this.enableMethods(ConfigActivity.WRITING_METHOD_PREFERENCE, R.id.writing_chart, true, true);

            removeDialog(LESSON_MENU_DIALOG);
            removeDialog(CROSS_LEARN_DIALOG);
        } else if ( requestCode == REQUEST_CODE_LEARNING ) {
            Editor editor = this.settings.edit();
            editor.putBoolean(FixLangActivity.MODIFY_HISTORY_FLAG, true);
            editor.commit();
        	
        	this.refreshLessons();
        }
    }
	
	private class CustomCursorAdapter extends SimpleCursorAdapter implements OnCheckedChangeListener {

		private SparseBooleanArray checkArray = new SparseBooleanArray();
		private boolean prevent = false;
		
		public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);

			this.setViewBinder( new SimpleCursorAdapter.ViewBinder() {			
				@Override
				public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
					if ( columnIndex == countColIndex ) {
				    	int count = cursor.getInt(columnIndex);
				    	String text = count + " ";
				    	if ( count == 1 ) {
				    		text += getString( R.string.oneword );
				    	} else if ( count >= 1 && count <= 4 ) {
				    		text += getString( R.string.twofourword );
				    	} else {
				    		text += getString( R.string.restword );
				    	}	    	
				    	((TextView)view).setText(text); 					
						return true;
					} else if ( columnIndex == questioningColIndex ) {
						if ( questioningEnabled ) {
							view.setVisibility(View.VISIBLE);
							view.getLayoutParams().height = calcChartHeight( LESSON_ROW_HEIGHT, cursor.getInt(columnIndex), cursor.getInt(countColIndex) );						
						} else {
							view.setVisibility(View.GONE);
						}
						return true;					
					} else if ( columnIndex == answeringColIndex ) {
						if ( answeringEnabled ) {
							view.setVisibility(View.VISIBLE);
							view.getLayoutParams().height = calcChartHeight( LESSON_ROW_HEIGHT, cursor.getInt(columnIndex), cursor.getInt(countColIndex) );						
						} else {
							view.setVisibility(View.GONE);
						}
						return true;
					} else if ( columnIndex == writingColIndex ) {
						if ( writingEnabled ) {
							view.setVisibility(View.VISIBLE);
							view.getLayoutParams().height = calcChartHeight( LESSON_ROW_HEIGHT, cursor.getInt(columnIndex), cursor.getInt(countColIndex) );						
						} else {
							view.setVisibility(View.GONE);
						}
						return true;
					} else if ( columnIndex == listeningColIndex ) {
						if ( listeningEnabled ) {
							view.setVisibility(View.VISIBLE);
							view.getLayoutParams().height = calcChartHeight( LESSON_ROW_HEIGHT, cursor.getInt(columnIndex), cursor.getInt(countColIndex) );													
						} else {
							view.setVisibility(View.GONE);
						}
						return true;
					}
					return false;
				}
				
			});		
		}
				
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup viewgroup) {	        			        		
			View v = super.newView(context, cursor, viewgroup);
			
			if ( v.getTag() == null ) {				
				CheckBox check = (CheckBox)v.findViewById(R.id.checklesson);
				check.setOnCheckedChangeListener(this);	        	
				v.setTag( check );
			}
			return v;
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) {						
			CheckBox c = (CheckBox)view.getTag();
			c.setTag( cursor.getPosition() );
			prevent = true;
			try {
				c.setChecked( checkArray.get( cursor.getPosition(), false ) );
			} finally {
				prevent = false;
			}
			super.bindView(view, context, cursor);
		}
        	
		@Override
		public void onCheckedChanged(CompoundButton checkbox, boolean isChecked) {
			if ( !prevent ) {
				int pos = (Integer)checkbox.getTag();
				checkArray.put( pos, isChecked );

				boolean checked = false;
				for (int i = 0; i <  checkArray.size(); i++) {
					if ( checkArray.valueAt(i) ) {
						checked = true;
						break;
					}
				}
				
				selectionCheck.setEnabled( checked );
				selectionCheck.setChecked( checked );				
			}
		}    

		public void close() {
			if ( this.getCursor() != null ) {
				this.getCursor().close();
			}
		}

		public void requery() {
			if ( this.getCursor() != null ) {
				this.getCursor().requery();
			}
		}
		
		public List<Integer> selectedPositions() {						
			List<Integer> result = new ArrayList<Integer>();
			for ( int i = 0; i < checkArray.size(); i++ ) {
				if ( checkArray.valueAt( i ) ) {
					result.add( checkArray.keyAt(i) );
				}
			}
			return result;
		}
	
		public void clearChecked() {
			this.checkArray.clear();
		}
	}
	
}
